package com.bx.imserver.utils;







import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.*;
import java.util.stream.Collectors;

public class ScanFilesWithRecursionUtils {
    private static ArrayList<Map> scanFiles = new ArrayList<>();
    private static int count=0;
    static List <Tree> node= new LinkedList();

    /**
     * TODO:递归扫描指定文件夹下面的指定文件
     * @return ArrayList<Object>
     * @throws FileNotFoundException
     */
    public static String scanFilesWithRecursion(String folderPath) throws IOException {
        String batPath = "";
        File directory = new File(folderPath);
        List<Map> list=new ArrayList<>();
        if(!directory.isDirectory()){
            throw new FileNotFoundException('"' + folderPath + '"' + " input path is not a Directory , please input the right path of the Directory. ^_^...^_^");
        }
        if(directory.isDirectory()){
            File [] filelist = directory.listFiles();
            for(int i = 0; i < filelist.length; i ++){
                /**如果当前是文件夹，进入递归扫描文件夹**/
                if(filelist[i].isDirectory()){
                    /**递归扫描下面的文件夹**/
                    count++;
                    scanFilesWithRecursion(filelist[i].getAbsolutePath());
                }
                /**非文件夹**/
                else{
                    while(filelist[i].getName().contains(".bat")){
                        batPath = filelist[i].getPath();
                        break;
                    }
                }
            }
        }
        return batPath;
    }
    public static Tree scanFileTree(String paths) throws IOException {
        ArrayList<Tree> treelist= new ArrayList<>();
        node.removeAll(node);
        int level=0;
        List<Tree> file = getFile(paths, 1, level);
        Tree tree = new Tree();
        tree.setPId(-2);
        tree.setId(0);
        tree.setName(paths);
        Map<Integer, Tree> collect = file.stream().collect(Collectors.toMap(Tree::getId, a -> a, (k1, k2) -> k1));
        for (Tree menu : file) {
            if (null == collect.get(menu.getPId())) {
                treelist.add(menu);
            } else {
                // 子级通过父id获取到父级的类型
                Tree parent = collect.get(menu.getPId());
                // 父级获得子级，再将子级放到对应的父级中
                parent.addChildren(menu);
            }
        }
        tree.setChildren(treelist);
        return tree;
    }
    private static List<Tree> getFile(String path, int id, int pid) {
        File file = new File(path);
        // 此处改为 file.exist可收集文件夹下的所有文件
        if(file.isDirectory()) {
            File[] array = file.listFiles();
            List fileList = Arrays.asList(array);
            //对读到的本地文件夹进行排序
            Collections.sort(fileList, new Comparator<File>() {
                @Override
                public int compare(File o1, File o2) {
                    if (o1.isDirectory() && o2.isFile()) {
                        return -1;
                    }
                    if (o1.isFile() && o2.isDirectory()){
                        return 1;
                    }
                    return o1.getName().compareTo(o2.getName());
                }
            });

            for (int i = 0; i < array.length; i++) {
                Tree tree = new Tree();
                tree.setPId(pid);
                tree.setId(id);
                tree.setName(array[i].getName());
                //判断是否为文件夹，是的话进行递归
                if (array[i].isDirectory()) {
                    node.add(tree);
                    //进行递归，此时的pid为上一级的id
                    getFile(array[i].getPath(), id * 10 + 1 + i, id);
                    id++;
                }
                // 此处放开可添加文件夹下的文件
/*                else {
                    node.add(tree);
                    id++;
                }*/
            }
        }
        else
        {
            System.out.println("文件不存在");
        }
        return node;
    }

    public static String getJdkFileMD5(String path) {

        try {

            BigInteger bi = null;

            byte[] buffer = new byte[1024 * 4];

            int len = 0;

            MessageDigest md = MessageDigest.getInstance("MD5");

            File f = new File(path);

            FileInputStream fis = null;

            fis = new FileInputStream(f);

            while ((len = fis.read(buffer)) != -1) {

                md.update(buffer, 0, len);

            }

            fis.close();

            byte[] b = md.digest();

            bi = new BigInteger(1, b);

            return bi.toString(16);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }
    /*public static boolean moveFiles(String oldPath, String newPath){
        boolean result = true;
        String[] filePaths = new File(oldPath).list();

        if (filePaths != null && filePaths.length > 0){
            if (!new File(newPath).exists()){
                if(!new File(newPath).mkdirs()){
                    System.out.println("文件夹创建失败");
                    return false;
                }
            }
            try{
                for (String filePath : filePaths) {
                    if (new File(oldPath + File.separator + filePath).isDirectory()){
                        moveFiles(oldPath + File.separator + filePath, newPath + File.separator + filePath);
                    }else if (new File(oldPath + File.separator + filePath).isFile()){
                        //复制文件到另一个目录
                        copyFile(oldPath + File.separator + filePath, newPath + File.separator + filePath);
                        //移动文件至另一个目录
                        if(!new File(oldPath + File.separator + filePath).renameTo(new File(newPath + File.separator + filePath))){
                            System.out.println(oldPath + File.separator + filePath +"文件复制失败");
                            result = false;
                            break;
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return result;
    }

    public static void copyFile(String oldPath, String newPath) throws IOException {
        File oldFile = new File(oldPath);
        File file = new File(newPath);
        FileInputStream in = new FileInputStream(oldFile);
        FileOutputStream out = new FileOutputStream(file);
        byte[] buffer=new byte[2097152];
        while((in.read(buffer)) != -1){
            out.write(buffer);
        }
    }*/

    /**
     * 剪切或复制
     * @param folderPath
     * @throws IOException
     */
    public static void copyGeneralFile(String folderPath) throws IOException {
        File directory = new File(folderPath);
        if(!directory.isDirectory()){
            throw new FileNotFoundException('"' + folderPath + '"' + " input path is not a Directory , please input the right path of the Directory. ^_^...^_^");
        }
        if(directory.isDirectory()){
            File [] filelist = directory.listFiles();
            for(int i = 0; i < filelist.length; i ++){
                /**如果当前是文件夹，进入递归扫描文件夹**/
                if(filelist[i].isDirectory()){
                    /**递归扫描下面的文件夹**/
                    count++;
                    System.out.println(count);
                    copyGeneralFile(filelist[i].getAbsolutePath());
                    System.out.println("filelist[i].getName()===="+filelist[i].getName());
                }
                /**非文件夹**/
                else{
                    System.out.println("filelist[i].getName()===="+filelist[i].getName());
                    while(filelist[i].getName().contains("$$")){
                        //复制
                        BackupFileUtil.copyGeneralFile(filelist[i].getAbsolutePath(),"F://temp//");
                        //剪切
                        BackupFileUtil.cutGeneralFile(filelist[i].getAbsolutePath(),"F://temp//");
                        break;
                    }
                }
            }
        }
    }

    /**
     * 清空文件及文件夹
     * @param path
     * @return
     */
    public static boolean deleteDir(String path){
        File file = new File(path);
        if(!file.exists()){//判断是否待删除目录是否存在
            System.err.println("The dir are not exists!");
            return false;
        }

        String[] content = file.list();//取得当前目录下所有文件和文件夹
        for(String name : content){
            File temp = new File(path, name);
            if(temp.isDirectory()){//判断是否是目录
                deleteDir(temp.getAbsolutePath());//递归调用，删除目录里的内容
                temp.delete();//删除空目录
            }else{
                if(!temp.delete()){//直接删除文件
                    System.err.println("Failed to delete " + name);
                }
            }
        }
        return true;
    }


}
